<template>
  <div class="question-bank-container">
    <div class="header">
      <h2>题库管理</h2>
      <el-button type="primary" @click="openAddDialog">添加题目</el-button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="学科">
          <el-select 
            v-model="filter.subjectId" 
            placeholder="选择学科" 
            clearable 
            @change="handleFilterChange"
            style="width: 180px;"
          >
            <el-option 
              v-for="item in subjectList" 
              :key="item.id" 
              :label="item.subject || item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select 
            v-model="filter.type" 
            placeholder="选择题目类型" 
            clearable 
            @change="handleFilterChange"
            style="width: 180px;"
          >
            <el-option label="选择题" :value="0" />
            <el-option label="应用题" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilterChange">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 题目列表 -->
    <div v-loading="loading" class="question-list">
      <el-empty v-if="!loading && questionList.length === 0" description="暂无题目数据" />
      
      <div v-else class="question-cards">
        <el-card v-for="question in questionList" :key="question.id" class="question-card">
          <div class="question-header">
            <span class="question-type" :class="question.type === 0 ? 'type-choice' : 'type-application'">
              {{ question.type === 0 ? '选择题' : '应用题' }}
            </span>
            <span class="question-subject">{{ question.subjectName }}</span>
          </div>
          
          <div class="question-content">
            <div class="question-title">
              <MathFormula :formula="question.question" :display-mode="true" />
            </div>
            
            <!-- 选择题选项 - 默认不显示正确答案 -->
            <div v-if="question.type === 0" class="options-list">
              <div 
                v-for="(option, index) in question.options" 
                :key="index" 
                class="option-item"
                :class="{ 'correct-option': showAnswers[question.id] && option.isCorrect }"
              >
                <span class="option-label">{{ ['A', 'B', 'C', 'D'][index] }}.</span>
                <span class="option-content">
                  <MathFormula :formula="option.content" />
                </span>
              </div>
            </div>
            
            <!-- 应用题答案 - 默认不显示 -->
            <div v-if="question.type === 1 && showAnswers[question.id]" class="application-answer">
              <div class="answer-label">参考答案:</div>
              <div class="answer-content">
                <MathFormula :formula="question.answer" :display-mode="true" />
              </div>
            </div>
          </div>
          
          <div class="question-actions">
            <el-button type="success" size="small" @click="toggleAnswer(question.id)">
              {{ showAnswers[question.id] ? '隐藏答案' : '查看答案' }}
            </el-button>
            <el-button type="primary" size="small" @click="openEditDialog(question)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(question)">删除</el-button>
          </div>
        </el-card>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingQuestion.id ? '编辑题目' : '添加题目'"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="questionForm"
        :model="editingQuestion"
        :rules="rules"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="学科" prop="subject">
          <el-select v-model="editingQuestion.subject" placeholder="选择学科" style="width: 100%">
            <el-option 
              v-for="item in subjectList" 
              :key="item.id" 
              :label="item.subject" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目类型" prop="type">
          <el-radio-group v-model="editingQuestion.type">
            <el-radio :label="0">选择题</el-radio>
            <el-radio :label="1">应用题</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="题目" prop="question">
          <el-input 
            v-model="editingQuestion.question" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入题目内容"
          />
        </el-form-item>
        
        <!-- 选择题选项 -->
        <template v-if="editingQuestion.type === 0">
          <el-divider content-position="left">选项</el-divider>
          
          <div v-for="(option, index) in editingQuestion._options" :key="index" class="option-form-item">
            <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item :label="`选项 ${['A', 'B', 'C', 'D'][index]}`" :prop="`_options.${index}.content`" :rules="{ required: true, message: '请输入选项内容', trigger: 'blur' }">
                  <el-input v-model="option.content" placeholder="请输入选项内容" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="正确答案">
                  <el-checkbox v-model="option.isCorrect" @change="handleCorrectChange(index)" />
                </el-form-item>
              </el-col>
              <el-col :span="2" v-if="editingQuestion._options.length > 2">
                <el-button 
                  type="danger" 
                  circle 
                  icon="Delete" 
                  size="small" 
                  style="margin-top: 40px;"
                  @click="removeOption(index)"
                />
              </el-col>
            </el-row>
          </div>
          
          <div class="add-option-btn" v-if="editingQuestion._options.length < 4">
            <el-button type="primary" plain @click="addOption">添加选项</el-button>
          </div>
        </template>
        
        <!-- 应用题答案 -->
        <template v-else>
          <el-form-item label="参考答案" prop="answer">
            <el-input 
              v-model="editingQuestion.answer" 
              type="textarea" 
              :rows="5" 
              placeholder="请输入参考答案"
            />
          </el-form-item>
        </template>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveQuestion" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import axios from 'axios'
import MathFormula from '../components/MathFormula.vue'

// 状态变量
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const questionList = ref([])
const subjectList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 控制答案显示的状态
const showAnswers = reactive({})

// 筛选条件
const filter = reactive({
  subjectId: '',  // 学科ID
  type: ''      // 题目类型（0表示选择题，1表示应用题）
})

// 编辑中的题目
const editingQuestion = reactive({
  id: null,
  subjectId: '',  // 学科ID
  type: 0,      // 0表示选择题，1表示应用题
  question: '', // 题目内容
  answer: '',   // 答案（对于选择题是JSON字符串，应用题是纯文本）
  status: 1,    // 状态，默认1表示正常
  
  // 前端使用的临时字段，不会发送给后端
  _subjectName: '',
  _options: [
    { content: '', isCorrect: false },
    { content: '', isCorrect: false }
  ]
})

// 表单验证规则
const rules = {
  subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
  type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  question: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
  answer: [{ 
    required: true, 
    message: '请输入参考答案', 
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (editingQuestion.type === 1 && !value) {
        callback(new Error('请输入参考答案'))
      } else {
        callback()
      }
    }
  }]
}

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const response = await axios.get('/api/subject/list')
    console.log('学科列表原始响应:', response.data)
    if (response.data.code === '200') {
      let arr = response.data.data?.data
      if (!Array.isArray(arr)) arr = []
      // 打印每个学科的字段
      arr.forEach(subject => {
        console.log('学科字段:', Object.keys(subject))
        console.log('学科数据:', subject)
      })
      subjectList.value = arr
      console.log('学科列表处理后:', subjectList.value)
      
      // 如果已经获取了题目列表，重新处理学科名称
      if (questionList.value.length > 0) {
        questionList.value = questionList.value.map(item => {
          const subjectObj = subjectList.value.find(s => s.id === item.subject)
          if (subjectObj) {
            item.subjectName = subjectObj.subject
          }
          return item
        })
      }
    }
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  }
}

// 获取题目列表
const fetchQuestionList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    if (filter.subjectId) {
      params.subjectId = filter.subjectId
    }
    
    if (filter.type !== '') {
      params.type = filter.type
    }
    
    // 调用后端API
    const response = await axios.get('/api/question/list', { params })
    
    // 处理响应数据
    if (response.data.code === '200') {
      // 将后端数据转换为前端显示格式
      // 根据后端返回的数据结构调整获取方式
      const records = response.data.data.data || []
      console.log('题目列表原始数据:', records)
      
      // 如果学科列表为空，先获取学科列表
      if (subjectList.value.length === 0) {
        await fetchSubjectList()
      }
      
      questionList.value = records.map(item => {
        // 找到对应的学科名称
        const subjectObj = subjectList.value.find(s => s.id === item.subjectId)
        const subjectName = subjectObj ? subjectObj.subject : `学科${item.subject}`
        
        // 处理数学表达式的函数
        const processMathExpression = (text) => {
          // 直接返回原始文本，不做任何处理
          // 这样可以保留原始的 $$ 符号，使 MathJax 可以正确渲染
          if (!text) return text;
          console.log('保留原始数学表达式:', text);
          return text;
        }
        
        // 处理选择题选项
        let options = []
        if (item.type === 0) { // 选择题
          try {
            options = JSON.parse(item.answer || '[]')
          } catch (e) {
            console.error('解析选项失败:', e)
            options = []
          }
        }
        
        return {
          id: item.id,
          subject: item.subject,
          subjectName: subjectName,
          type: item.type, // 0表示选择题，1表示应用题
          question: item.question, // 使用question而非title
          options: options,
          answer: item.type === 1 ? item.answer : '',
          createTime: item.createTime
        }
      })
      
      console.log('处理后的题目列表:', questionList.value)
      
      total.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 重置筛选条件
const resetFilter = () => {
  filter.subjectId = ''
  filter.type = ''
  handleFilterChange()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchQuestionList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchQuestionList()
}

// 切换答案显示状态
const toggleAnswer = (questionId) => {
  // 使用Vue的响应式系统来更新状态
  if (showAnswers[questionId]) {
    // 如果已经显示，则隐藏
    showAnswers[questionId] = false
  } else {
    // 如果未显示，则显示
    showAnswers[questionId] = true
  }
}

// 处理数学表达式的函数
const processMathExpression = (text) => {
  // 直接返回原始文本，不做任何处理
  // 这样可以保留原始的 $$ 符号，使 MathJax 可以正确渲染
  return text || ''
}

// 初始化数据
const initData = () => {
  // 获取学科列表
  fetchSubjectList()
  
  // 获取题目列表
  fetchQuestionList()
}

// 打开添加题目对话框
const openAddDialog = () => {
  // 初始化编辑对象
  editingQuestion.id = null
  editingQuestion.subject = ''
  editingQuestion.type = 0
  editingQuestion.question = ''
  editingQuestion._options = [
    { content: '', isCorrect: true },
    { content: '', isCorrect: false }
  ]
  editingQuestion.answer = ''
  editingQuestion.status = 1
  
  // 打开对话框
  dialogVisible.value = true
}

// 打开编辑题目对话框
const openEditDialog = (question) => {
  // 深拷贝题目对象
  const questionCopy = JSON.parse(JSON.stringify(question))
  
  // 处理选项数据
  if (questionCopy.type === 0) {
    questionCopy._options = questionCopy.options || []
    delete questionCopy.options
  } else {
    questionCopy._options = []
  }
  
  // 将title转换为question
  if (questionCopy.title && !questionCopy.question) {
    questionCopy.question = questionCopy.title
    delete questionCopy.title
  }
  
  Object.assign(editingQuestion, questionCopy)
  
  // 打开对话框
  dialogVisible.value = true
}

// 处理删除题目
const handleDelete = (question) => {
  ElMessageBox.confirm(
    '确定要删除这个题目吗？此操作不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用后端API
      const response = await axios.delete(`/api/question/${question.id}/delete`)
      
      if (response.data.code === '200') {
        ElMessage.success('删除成功')
        fetchQuestionList()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除题目失败:', error)
      ElMessage.error('删除题目失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 添加选项
const addOption = () => {
  if (editingQuestion._options.length < 4) {
    editingQuestion._options.push({ content: '', isCorrect: false })
  }
}

// 移除选项
const removeOption = (index) => {
  if (editingQuestion._options.length > 2) {
    // 如果删除的是正确选项，需要重新处理
    if (editingQuestion._options[index].isCorrect) {
      // 如果只有一个正确选项，则将第一个选项设为正确
      const correctCount = editingQuestion._options.filter(o => o.isCorrect).length
      if (correctCount === 1) {
        editingQuestion._options[0].isCorrect = true
      }
    }
    
    editingQuestion._options.splice(index, 1)
  }
}

// 处理正确答案变更
const handleCorrectChange = (index) => {
  // 单选题逻辑：只允许一个正确答案
  if (editingQuestion._options[index].isCorrect) {
    // 将其他选项设为错误
    editingQuestion._options.forEach((option, i) => {
      if (i !== index) {
        option.isCorrect = false
      }
    })
  } else {
    // 如果取消了唯一的正确答案，则将第一个选项设为正确
    const correctCount = editingQuestion._options.filter(o => o.isCorrect).length
    if (correctCount === 0) {
      editingQuestion._options[0].isCorrect = true
    }
  }
}

// 关闭对话框
const handleDialogClose = (done) => {
  done()
}

// 保存题目
const saveQuestion = async () => {
  // 表单验证
  const questionForm = document.querySelector('.el-form')
  
  // 验证选择题选项
  if (editingQuestion.type === 0) { // 选择题
    // 检查是否有空选项
    const hasEmptyOption = editingQuestion._options.some(option => !option.content)
    if (hasEmptyOption) {
      ElMessage.error('请填写所有选项内容')
      return
    }
    
    // 检查是否有正确答案
    const hasCorrectOption = editingQuestion._options.some(option => option.isCorrect)
    if (!hasCorrectOption) {
      ElMessage.error('请至少选择一个正确答案')
      return
    }
  }
  
  // 验证应用题答案
  if (editingQuestion.type === 1 && !editingQuestion.answer) {
    ElMessage.error('请填写参考答案')
    return
  }
  
  saving.value = true
  try {
    // 构建保存数据
    const saveData = {
      id: editingQuestion.id,
      subjectId: editingQuestion.subject,
      type: editingQuestion.type,
      question: editingQuestion.question,
      status: editingQuestion.status || 1
    }
    
    // 处理答案
    if (editingQuestion.type === 0) { // 选择题
      // 将选项数据转换为JSON字符串
      saveData.answer = JSON.stringify(editingQuestion._options)
    } else { // 应用题
      saveData.answer = editingQuestion.answer
    }
    
    // 调用后端API
    const response = await axios.post('/api/question/add', saveData)
    
    if (response.data.code === '200') {
      ElMessage.success(editingQuestion.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      fetchQuestionList()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存题目失败:', error)
    ElMessage.error('保存题目失败')
  } finally {
    saving.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSubjectList()
  fetchQuestionList()
})
</script>

<style scoped>
.math-content {
  font-size: 16px;
  line-height: 1.6;
  margin: 8px 0;
}

/* 确保数学公式正确显示 */
.math-content :deep(.MathJax) {
  display: inline-block;
  margin: 0 2px;
  vertical-align: middle;
}

.question-bank-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #85c5ff 100%);
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
  color: white;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.filter-section {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.question-list {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  min-height: 400px;
}

.question-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.question-card {
  height: 100%;
  transition: all 0.3s ease;
}

.question-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.question-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.type-choice {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.type-application {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.question-subject {
  font-size: 13px;
  color: #606266;
}

.question-content {
  margin-bottom: 15px;
}

.question-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 10px;
  line-height: 1.5;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  padding: 5px 0;
}

.correct-option {
  color: #67c23a;
}

.option-label {
  font-weight: 500;
}

.application-answer {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 6px;
  margin-top: 10px;
}

.answer-label {
  font-weight: 500;
  margin-bottom: 5px;
  color: #606266;
}

.answer-content {
  white-space: pre-line;
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
}

.question-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.option-form-item {
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.add-option-btn {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
